<script setup lang="ts">
import { ref, onBeforeMount, h } from "vue";
import { useI18n } from "vue-i18n";
import type { MrpUserSaleDataItem } from "@/api/statisticalManagement/mrpUserSaleData/index.d";
import {
  getMrpUserSaleData,
  setUserPrepareStockNum,
  mrpUserSaleDataExport,
  setMrpUserSaleDataRebuild
} from "@/api/statisticalManagement/mrpUserSaleData/index";
import { getWarehouseList } from "@/api/public";
import { Edit, Download, Refresh, View } from "@element-plus/icons-vue";
import TableView, { type TableColumnItem } from "@/components/Table";
import FormView, { type FormConfigItem } from "@/components/FormView";
import QueryView from "@/components/QueryList";
import { addDialog } from "@/components/ReDialog";
defineOptions({
  name: "MrpUserSaleData"
});
onBeforeMount(() => {
  getTableData();
  getWarehouseOptions();
});
const { t } = useI18n();
const isLoading = ref(false);
const listQuery = ref({
  goods_sku: "",
  tm: "",
  warehouse_id: "",
  page: 1,
  limit: 20
});
const warehouseList = ref([]);
const tableTotal = ref(0);
const dialogVisible = ref(false);
const expandRowKeys = ref([]);
const tableData = ref<MrpUserSaleDataItem[]>([]);
const tableList: TableColumnItem[] = [
  {
    prop: "goods_img",
    label: "图片",
    propsType: "images"
  },
  {
    prop: "goods_sku",
    label: "sku"
  },
  {
    prop: "warehouse_name",
    label: "仓库名称"
  },
  {
    prop: "list",
    label: "产品信息",
    propsType: "list",
    formList: [
      {
        prop: "tm",
        label: "条码"
      },
      {
        prop: "goods_spec",
        label: "规格"
      },
      {
        prop: "goods_sku",
        label: "sku"
      }
    ]
  }
];
const formList: FormConfigItem[] = [
  {
    label: "sku",
    prop: "goods_sku",
    type: "input"
  },
  {
    label: "条码",
    prop: "tm",
    type: "input"
  },
  {
    label: "仓库",
    prop: "warehouse_id",
    type: "select",
    options: []
  },
  {
    label: "创建时间",
    prop: "create_time",
    type: "datePicker"
  }
];

/**
 * @description: 获取表格数据
 */

async function getTableData() {
  isLoading.value = true;
  const {
    data: { list, total }
  } = await getMrpUserSaleData(listQuery.value);
  isLoading.value = false;
  tableTotal.value = total || 0;
  tableData.value = list || [];
}

/**
 * @description: 获取仓库options
 */
async function getWarehouseOptions() {
  const itemOptions = formList.find(item => item.prop === "warehouse_id");
  const {
    data: { list }
  } = await getWarehouseList();
  itemOptions.options = list.map(item => {
    return {
      label: item.name,
      value: item.id
    };
  });
}

/**
 * @description: 搜索
 * @param {*} data
 */
function handleSearch(data: { [key: string]: any }) {
  listQuery.value = { ...listQuery.value, ...data };
  getTableData();
}

/**
 * @description: 设置备货数量
 * @param {} row
 */
async function handleSave(
  data: MrpUserSaleDataItem | MrpUserSaleDataItem[],
  type: "singe" | "batch",
  index?: number
) {
  const nowData = Array.isArray(data) ? data : [data];
  const ids = nowData.map(x => x.id);
  const stockNum = nowData[0].user_prepare_stock_num;
  // 提取保存库存数量的通用逻辑
  const saveStockNum = async (stockNum: string) => {
    return new Promise(async (_resolve, reject) => {
      try {
        await setUserPrepareStockNum({ ids, user_prepare_stock_num: stockNum });
        getTableData();
      } catch (error) {
        reject(error);
      }
    });
  };
  // 处理批量操作
  if (type === "batch") {
    addDialog({
      width: "400px",
      title: t("设置备货数量"),
      props: {
        formList: [
          {
            label: t("备货数量"),
            prop: "user_prepare_stock_num",
            required: true,
            min: 0,
            type: "input",
            labelWidth: "90px"
          }
        ],
        formData: { user_prepare_stock_num: "" }
      },
      contentRenderer: ({ options: { props } }) =>
        h(FormView, {
          formList: props.formList,
          modelValue: props.formData,
          labelPosition: "top",
          ref: "formViewRef"
        }),
      async beforeSure(done, { options: { props }, formViewRef, btn }) {
        try {
          await formViewRef.$refs.formRef.validate();
          btn.loading = true;
          saveStockNum(props.formData.user_prepare_stock_num);
          btn.loading = false;
          done();
        } catch (error) {
          btn.loading = false;
          console.error(error);
        }
      }
    });
  }
}

/**
 * @description: 重新生成
 */
async function handleRebuild(row) {}

const handleSelectionChange = (row: MrpUserSaleDataItem[]) => {
  console.log(row);
};
</script>

<template>
  <div class="page-view">
    <div class="top-view">
      <QueryView :queryList="formList" @search="handleSearch" />
    </div>
    <div class="bottom-view">
      <TableView
        :isLoading="isLoading"
        :page="listQuery.page"
        :total="tableTotal"
        :limit="listQuery.limit"
        :columns="tableList"
        :tableData="tableData"
        :expandRowKeys="expandRowKeys"
        :tableOptionsArr="['expand', 'selection']"
        @pagination="handleSearch"
        @selection-change="handleSelectionChange"
      >
        <template v-slot:default="{ row }">
          <el-button
            :icon="View"
            type="primary"
            @click="handleSave(row, 'batch')"
          >
            {{ "详情" }}
          </el-button>
          <el-button :icon="View" type="primary" @click="handleRebuild(row)">
            {{ "详情" }}
          </el-button>
          <el-button :icon="View" type="primary" @click="handleRebuild(row)">
            {{ "详情" }}
          </el-button>
          <el-button :icon="View" type="primary" @click="handleRebuild(row)">
            {{ "详情" }}
          </el-button>
        </template>
        <template v-slot:expand>
          <div>{{ "row" }}</div>
          <div>{{ "row" }}</div>
          <div>{{ "row" }}</div>
        </template>
      </TableView>
    </div>
  </div>
</template>
<style lang="scss" scoped>
// 按钮组样式
:deep(.el-button) {
  & + .el-button {
    margin-left: 0;
  }
}
</style>
